import sys
import os
import subprocess
import re
import shutil

def find_wav_file(logs, search_text):
    """
    从日志中搜索文本，并找到最近的wav文件路径。
    注意: 搜索的文本必须出现在行尾
    """
    lines = logs.split('\n')
    found_text = False

    for i, line in enumerate(reversed(lines)):
        if line.rstrip().endswith(search_text):
            print(f"找到文本: '{line}'")
            found_text = True
            # 从找到的位置向上搜索wav文件
            for j in range(i, len(lines)):
                line_to_check = lines[len(lines) - 1 - j]
                wav_match = re.search(r'/[^\s]*\.wav', line_to_check)
                if wav_match:
                    return wav_match.group(0)

    return None

def process_query(query):
    """
    处理查询并从docker中获取音频文件
    """
    try:
        # 获取docker容器日志到临时文件
        container_name = "voice2text"
        temp_log_file = "v2t-temp.log"
        log_cmd = ['docker', 'logs', '-n', '20000', container_name]

        with open(temp_log_file, 'w', encoding='utf-8') as f:
            subprocess.run(log_cmd, stdout=f, stderr=f, check=True)

        # 读取临时日志文件
        with open(temp_log_file, 'r', encoding='utf-8') as f:
            logs = f.read()

        # 删除临时日志文件
        os.remove(temp_log_file)

        # 确保音频文件目录存在并且清空
        audio_folder = 'audio_files'
        if os.path.exists(audio_folder):
            shutil.rmtree(audio_folder)

        os.makedirs(audio_folder)

        # 在日志中搜索wav文件
        wav_path = find_wav_file(logs, query)
        if not wav_path:
            print(f"未找到与查询 '{query}' 相关的 wav 文件")
            return False

        # 构建目标文件路径
        filename = os.path.basename(wav_path)
        target_path = os.path.join(audio_folder, filename)

        # 从docker容器中复制文件
        copy_cmd = ['docker', 'cp', f"{container_name}:{wav_path}", target_path]
        subprocess.run(copy_cmd, check=True)

        print(f"成功复制文件到: {target_path}")
        return True

    except subprocess.CalledProcessError as e:
        print(f"执行命令时出错: {e}")
        return False
    except Exception as e:
        print(f"处理查询时出错: {e}")
        return False
    finally:
        # 确保临时文件被删除
        if os.path.exists('v2t-temp.log'):
            try:
                os.remove('v2t-temp.log')
            except:
                pass

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("请提供搜索查询参数")
        sys.exit(1)

    query = sys.argv[1]
    success = process_query(query)
